import java.util.PriorityQueue;

// 自己实现  定时器
class MyTimerTask implements  Comparable<MyTimerTask> {
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public long getTime() {
        return time;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    //创建小根堆  用来存放MyTimeTask
    private PriorityQueue<MyTimerTask> taskQuque = new PriorityQueue<>();

    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (this) {
                        if (taskQuque.size() == 0) {
                            this.wait();
                        }
                        MyTimerTask task = taskQuque.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            //执行任务
                            task.run();
                            taskQuque.poll();
                        } else {
                            this.wait(task.getTime() - curTime);
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }

    public synchronized void schedule(Runnable runnable, long delay) {
        MyTimerTask task = new MyTimerTask(runnable, delay);
        taskQuque.offer(task);
        //当添加新的任务等待时间之后唤醒wait  重新拿到小根堆head
        this.notify();
    }

}

public class Demo36 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
    }
}
